<template>
  <div class="impression-container">
    <div class="header">
      <h2>曝光日志</h2>
      <div class="time-filter">
        <span>当前模拟时间：</span>
        <el-tag type="info">{{ formattedTime }}</el-tag>
        <el-button
            type="primary"
            size="small"
            :icon="Refresh"
            style="margin-left: 10px"
            @click="reloadCurrentView"
        >
          刷新
        </el-button>
      </div>
    </div>

    <div class="query-container">
      <span>用户ID：</span>
      <el-input
          v-model="queryParams.user_id"
          placeholder="用户ID"
          clearable
          style="width: 150px; margin-right: 10px"
      />
      <span>新闻ID：</span>
      <el-input
          v-model="queryParams.clicknews_id"
          placeholder="新闻ID"
          clearable
          style="width: 150px; margin-right: 10px"
      />
      <span>新闻分类：</span>
      <el-input
          v-model="queryParams.news_category"
          placeholder="新闻分类"
          clearable
          style="width: 150px; margin-right: 10px"
      />
      <span>新闻主题：</span>
      <el-input
          v-model="queryParams.news_topic"
          placeholder="新闻主题"
          clearable
          style="width: 180px; margin-right: 10px"
      />
      <el-button type="primary" @click="fetchData">查询</el-button>
      <el-button @click="resetQuery">重置</el-button>
    </div>

    <el-table
        :data="paginatedData"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        height="calc(100vh - 220px)"
        @sort-change="handleSortChange"
    >
      <el-table-column
          prop="SIMULATION_LOG_ID"
          label="日志ID"
          align="center"
          sortable="custom"
      />
      <el-table-column
          prop="USER_ID"
          label="用户ID"
          align="center"
          sortable="custom"
      />
      <el-table-column
          prop="CLICKNEWS_ID"
          label="新闻ID"
          align="center"
          sortable="custom"
      />
      <el-table-column
          prop="NEWS_CATEGORY"
          label="新闻分类"
          align="center"
          sortable="custom"
      >
        <template #default="{row}">
          <el-tag :type="getRandomTagType(row.NEWS_CATEGORY)">
            {{ row.NEWS_CATEGORY }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="NEWS_TOPIC"
          label="新闻主题"
          align="center"
          sortable="custom"
      >
        <template #default="{row}">
          <el-tag :type="getRandomTagType(row.NEWS_TOPIC)">
            {{ row.NEWS_TOPIC }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="DWELLTIME"
          label="停留时间(秒)"
          align="center"
          sortable="custom"
      >
        <template #default="{row}">
          <span :class="getDwellTimeClass(row.DWELLTIME)">{{ row.DWELLTIME }}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="EXPOSURE_TIME"
          label="曝光时间"
          align="center"
          sortable="custom"
      >
      <template #default="{row}">
        <span>{{ formatDateTime(new Date(row.EXPOSURE_TIME)) }}</span>
      </template>
      </el-table-column>>
      <el-table-column label="查看新闻内容" align="center" fixed="right">
        <template #default="{row}">
          <el-button type="text" size="small" @click="showNewsDetail(row.CLICKNEWS_ID)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="true"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="impressionData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新闻详情对话框 -->
    <el-dialog v-model="newsDetailVisible" title="新闻详情" width="60%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="新闻ID">{{ currentNews.NEWS_ID }}</el-descriptions-item>
        <el-descriptions-item label="分类">
          <el-tag :type="getRandomTagType(currentNews.CATEGORY)">
            {{ currentNews.CATEGORY }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="主题">
          <el-tag :type="getRandomTagType(currentNews.TOPIC)">
            {{ currentNews.TOPIC }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="标题">{{ currentNews.HEADLINE }}</el-descriptions-item>
        <el-descriptions-item label="内容">
          <div class="news-content">{{ currentNews.NEWS_BODY }}</div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="newsDetailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { useSimulationStore } from '@/store/simulation'
import { storeToRefs } from "pinia";
import axios from 'axios';
import {ElMessage} from "element-plus";

const simulationStore = useSimulationStore()

// 从store获取模拟时间
const { formattedTime,initialTime } = storeToRefs(simulationStore)
const { formatDateTime } = simulationStore
// 表格数据
const impressionData = ref([])
const currentNews = ref({})
const loading = ref(false)
const newsDetailVisible = ref(false)
// 查询参数
const queryParams = ref({
  user_id: '',
  clicknews_id: '',
  news_category: '',
  news_topic: ''
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  // 重置到第一页
  pagination.value.currentPage = 1
  try {
    const params = {
      exposure_time: formatDateTime(initialTime.value),
      ...queryParams.value
    }

    // 向后端发送请求
    const response = await axios.get('http://localhost:5000/query_simulation_logs', { params })

    if(!response.data.data){
      ElMessage.warning("未查询到相关数据！")
      return
    }
    impressionData.value = response.data.data
  }
  catch (error) {
    ElMessage.error('请求出错')
  }
  finally {
    loading.value = false
  }
}
// 显示新闻详情
const showNewsDetail = async (clicknews_id: any) => {
  try {
    const params = {
      news_id: clicknews_id
    }
    // 向后端发送请求
    const response = await axios.get('http://localhost:5000/get_news_by_id', { params })

    if (!response.data.data) {
      ElMessage.warning('未查询到相关数据')
      return
    }
    currentNews.value = response.data.data
    newsDetailVisible.value = true
  } catch (error) {
    ElMessage.error('请求出错')
  }
}


// 标签颜色类型
const tagTypes = ['', 'success', 'warning', 'danger', 'info']
// 存储已分配的标签颜色
const tagColorMap = new Map()
// 获取随机标签类型
const getRandomTagType = (tagName: string) => {
  if (!tagName) return ''

  // 如果已经分配过颜色，直接返回
  if (tagColorMap.has(tagName)) {
    return tagColorMap.get(tagName)
  }

  // 随机分配一个颜色类型
  const randomType = tagTypes[Math.floor(Math.random() * tagTypes.length)]
  tagColorMap.set(tagName, randomType)
  return randomType
}
// 根据停留时间获取样式类
const getDwellTimeClass = (time: number) => {
  if (time > 60) return 'long-dwell'
  if (time > 30) return 'medium-dwell'
  return 'short-dwell'
}


// 排序参数
const sortParams = ref({
  prop: '',
  order: ''
})
// 处理排序
const handleSortChange = ({ prop, order }) => {
  sortParams.value = { prop, order }
  // 这里可以根据实际需求实现排序逻辑
  // 如果是前端排序：
  if (order) {
    impressionData.value.sort((a, b) => {
      const valueA = a[prop]
      const valueB = b[prop]
      if (order === 'ascending') {
        return valueA > valueB ? 1 : -1
      } else {
        return valueA < valueB ? 1 : -1
      }
    })
  }
}
// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
})
// 计算分页后的数据
const paginatedData = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return impressionData.value.slice(start, end)
})
// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
}
// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val
}

// 重置查询
const resetQuery = async() => {
  queryParams.value = {
    user_id: '',
    clicknews_id: '',
    news_category: '',
    news_topic: ''
  }
  await fetchData()
}

// 重新加载界面
const reloadCurrentView = async() => {
  await resetQuery()
}
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.impression-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.time-filter {
  display: flex;
  align-items: center;
}

.query-container {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

/* 停留时间样式 */
.long-dwell {
  color: #67C23A;
  font-weight: bold;
}

.medium-dwell {
  color: #E6A23C;
}

.short-dwell {
  color: #F56C6C;
}

.news-content {
  white-space: pre-line;
  line-height: 1.6;
}
</style>